package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.Card;
import beans.Memory;

import com.sun.corba.se.spi.protocol.RequestDispatcherDefault;

/**
 * Servlet implementation class Spiellogik
 */
public class Spiellogik extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Spiellogik() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/memory.jsp");
		  try{
		  Memory memory = (Memory)request.getSession().getAttribute("memory");
		  int index = Integer.parseInt((String)request.getParameter("c").toString());
		  Card cardcurrent = memory.getFeld().get(index);
		  
		  System.out.println(memory.toString());
		  System.out.println("die karte nr: " + index);
		  
		  for(Card c : memory.getFeld()){
			  System.out.println("c: "+c+" ist aufgedeckt: "+ c.isHit());
			  System.out.println("old proof: "+memory.getProof());
			  System.out.println("are same: "+(memory.getProof()!=c));
			  if(memory.getProof()!=c)
				  c.setAufgedeckt(c.isHit());
		  }
		  
		  cardcurrent.setAufgedeckt(true);

		  if(memory.getProof()!=null){
			  if(cardcurrent.getUrl().equals(memory.getProof().getUrl())&&memory.getProof()!=cardcurrent){
				  if(!cardcurrent.isHit()&&!memory.getProof().isHit()){
				  memory.setGefundenePaare(memory.getGefundenePaare()+1);
				  memory.setRestlichePaare(memory.getRestlichePaare()-1);
				  cardcurrent.setHit(true);
				  memory.getProof().setHit(true);
				  System.out.println("HIT");
				  memory.setVersuche(memory.getVersuche()+1);
				  }
			  }
			  if((!cardcurrent.isHit())&&(memory.getProof()!=cardcurrent)){
				  memory.setVersuche(memory.getVersuche()+1);
			  }
			  memory.setProof(null);
		  }else{
			  memory.setProof(cardcurrent);
		  }
		  }catch(NullPointerException e){
			  e.printStackTrace();
		  }
		  
		  

		  dispatcher.forward(request, response);		  
	}

}
